/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package JFreeChartExtensions.chartextensions.utils;

import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.util.List;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.annotations.XYAnnotation;
import org.jfree.chart.annotations.XYTitleAnnotation;

/**
 *
 * @author Nobody
 */
public
class XYTitleAnnotationWrapper  {

    private XYTitleAnnotation annotation;
    private JFreeChart chart;
    private boolean visible;
    private Rectangle2D.Double lastUsedRect;

    public XYTitleAnnotation getAnnotation() {
        return annotation;
    }

    public void setLastUsedRect(Rectangle2D.Double lastUsedRect) {
        this.lastUsedRect = lastUsedRect;
    }

    public boolean isVisible() {
        return visible;
    }

    public XYTitleAnnotationWrapper(JFreeChart chart) {
        this.chart = chart;
        List<XYAnnotation> a = chart.getXYPlot().getAnnotations();
        this.visible = false;
        for (XYAnnotation item : a) {
            if (item instanceof XYTitleAnnotation) {
                this.annotation = (XYTitleAnnotation) item;
                this.visible = true;
                break;
            }
        }
    }

    public void setVisible(boolean visible) {
        if (visible) {
            createNewAnnotationBasedOn(lastUsedRect);
        } else {
            removeFromActiveAnnotation();
        }
        this.visible = visible;

    }

    public void setPosition(Rectangle.Double rect) {
        removeFromActiveAnnotation();
        createNewAnnotationBasedOn(rect);
        this.lastUsedRect = rect;
    }

    private void removeFromActiveAnnotation() {
        if (annotation != null) {
            chart.getXYPlot().removeAnnotation(annotation);
        }
    }

    public void createNewAnnotationBasedOn(Rectangle2D.Double rect) {
        annotation = new XYTitleAnnotation(rect.x, rect.y, chart.getLegend());
        annotation.setMaxWidth(rect.width);
        annotation.setMaxHeight(rect.height);
        chart.getXYPlot().addAnnotation(annotation);


    }
}

